package com.lwb.ztx.lives.widget;


import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.lwb.ztx.R;
import com.lwb.ztx.bean.LiveBean;
import com.lwb.ztx.lives.presenter.LivePresenter;
import com.lwb.ztx.lives.presenter.LivePresenterImpl;
import com.lwb.ztx.lives.view.LiveView;
import com.lwb.ztx.lives.view.content.LiveBeanFactory;

import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 */
public class LiveFragment extends Fragment implements LiveChannelAdapter.OnChannelItemClickListener, LiveView {

    RecyclerView recyclerView;
    LiveChannelAdapter adapter;
    private View rootView;

    private LivePresenter presenter;

    public LiveFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        if (rootView == null) {
            rootView = inflater.inflate(R.layout.fragment_live, container, false);
            recyclerView = (RecyclerView) rootView.findViewById(R.id.live_channel_list);
            GridLayoutManager gridLayoutManager = new GridLayoutManager(this.getActivity(),3);
            gridLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
            recyclerView.setLayoutManager(gridLayoutManager);
            adapter = new LiveChannelAdapter(this, LiveBeanFactory.getLiveBeans());
            recyclerView.setAdapter(adapter);
            presenter = new LivePresenterImpl(this);
            presenter.getLives(this.getActivity());
        }
        ViewGroup parentView = (ViewGroup) rootView.getParent();
        if (parentView != null) {
            parentView.removeView(rootView);
        }

        return rootView;
    }

    @Override
    public void onClickItem(LiveBean bean) {
        LivePlayActivity.allLives = adapter.getLiveBeanList();
        LivePlayActivity.index = LivePlayActivity.allLives.indexOf(bean);
        Intent intent = new Intent(this.getActivity(),LivePlayActivity.class);
        intent.putExtra("url",bean.getPath());
        intent.putExtra("title",bean.getTitle());
        this.getActivity().startActivity(intent);
    }

    @Override
    public void addLives(List<LiveBean> beans) {
        adapter.addLives(beans);
        adapter.notifyDataSetChanged();
    }
}
